"""
照明状态检测API接口
"""
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File
from typing import List, Optional
import base64
import cv2
import numpy as np
from datetime import datetime

from schemas.lighting_detection import (
    LightingDetectionRequest,
    LightingDetectionResponse,
    LightingAnomalyResponse,
    LightingZoneConfigRequest,
    LightingZoneConfigResponse,
    LightingStatsResponse,
    LightingServiceStatsResponse,
    LightingDetectionListRequest,
    LightingDetectionListResponse,
    LightingAnomalyListRequest,
    LightingAnomalyListResponse,
    LightingZoneStatsRequest,
    LightingZoneConfigListResponse
)
from services.lighting_detection_service import (
    lighting_detection_service,
    LightingZoneConfig
)

router = APIRouter(prefix="/lighting", tags=["照明检测"])


@router.post("/detect", response_model=LightingDetectionResponse)
async def detect_lighting_status(request: LightingDetectionRequest):
    """
    检测照明状态
    """
    try:
        # 解码图像数据
        if request.image_data:
            # 从Base64解码图像
            image_bytes = base64.b64decode(request.image_data)
            nparr = np.frombuffer(image_bytes, np.uint8)
            image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        else:
            # 如果没有提供图像，创建一个模拟图像
            image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
        
        # 执行照明检测
        result = await lighting_detection_service.detect_lighting_status(
            image=image,
            camera_id=request.camera_id,
            zone_id=request.zone_id
        )
        
        # 转换为响应格式
        return LightingDetectionResponse(
            detection_id=result.detection_id,
            camera_id=result.camera_id,
            zone_id=result.zone_id,
            timestamp=result.timestamp,
            lighting_status=result.lighting_status,
            brightness_level=result.brightness_level,
            natural_light_level=result.natural_light_level,
            artificial_light_level=result.artificial_light_level,
            lighting_type=result.lighting_type,
            color_temperature=result.color_temperature,
            uniformity_score=result.uniformity_score,
            detected_anomalies=result.detected_anomalies,
            energy_efficiency_score=result.energy_efficiency_score,
            recommendations=result.recommendations
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"照明检测失败: {str(e)}")


@router.post("/detect/upload", response_model=LightingDetectionResponse)
async def detect_lighting_from_upload(
    camera_id: str,
    zone_id: str,
    file: UploadFile = File(...)
):
    """
    通过上传图像检测照明状态
    """
    try:
        # 读取上传的图像文件
        contents = await file.read()
        nparr = np.frombuffer(contents, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise HTTPException(status_code=400, detail="无效的图像文件")
        
        # 执行照明检测
        result = await lighting_detection_service.detect_lighting_status(
            image=image,
            camera_id=camera_id,
            zone_id=zone_id
        )
        
        # 转换为响应格式
        return LightingDetectionResponse(
            detection_id=result.detection_id,
            camera_id=result.camera_id,
            zone_id=result.zone_id,
            timestamp=result.timestamp,
            lighting_status=result.lighting_status,
            brightness_level=result.brightness_level,
            natural_light_level=result.natural_light_level,
            artificial_light_level=result.artificial_light_level,
            lighting_type=result.lighting_type,
            color_temperature=result.color_temperature,
            uniformity_score=result.uniformity_score,
            detected_anomalies=result.detected_anomalies,
            energy_efficiency_score=result.energy_efficiency_score,
            recommendations=result.recommendations
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"照明检测失败: {str(e)}")


@router.post("/detections", response_model=LightingDetectionListResponse)
async def get_detection_results(request: LightingDetectionListRequest):
    """
    获取照明检测结果列表
    """
    try:
        results = await lighting_detection_service.get_detection_results(
            zone_id=request.zone_id,
            start_time=request.start_time,
            end_time=request.end_time,
            limit=request.limit
        )
        
        # 转换为响应格式
        detections = []
        for result in results:
            detection = LightingDetectionResponse(
                detection_id=result.detection_id,
                camera_id=result.camera_id,
                zone_id=result.zone_id,
                timestamp=result.timestamp,
                lighting_status=result.lighting_status,
                brightness_level=result.brightness_level,
                natural_light_level=result.natural_light_level,
                artificial_light_level=result.artificial_light_level,
                lighting_type=result.lighting_type,
                color_temperature=result.color_temperature,
                uniformity_score=result.uniformity_score,
                detected_anomalies=result.detected_anomalies,
                energy_efficiency_score=result.energy_efficiency_score,
                recommendations=result.recommendations
            )
            detections.append(detection)
        
        return LightingDetectionListResponse(
            detections=detections,
            total=len(detections)
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取检测结果失败: {str(e)}")


@router.post("/anomalies", response_model=LightingAnomalyListResponse)
async def get_lighting_anomalies(request: LightingAnomalyListRequest):
    """
    获取照明异常列表
    """
    try:
        anomalies = await lighting_detection_service.get_anomalies(
            zone_id=request.zone_id,
            anomaly_type=request.anomaly_type,
            severity=request.severity,
            limit=request.limit
        )
        
        # 转换为响应格式
        anomaly_responses = []
        for anomaly in anomalies:
            anomaly_response = LightingAnomalyResponse(
                anomaly_id=anomaly.anomaly_id,
                zone_id=anomaly.zone_id,
                camera_id=anomaly.camera_id,
                anomaly_type=anomaly.anomaly_type,
                severity=anomaly.severity,
                description=anomaly.description,
                detected_at=anomaly.detected_at,
                confidence=anomaly.confidence,
                location=anomaly.location
            )
            anomaly_responses.append(anomaly_response)
        
        return LightingAnomalyListResponse(
            anomalies=anomaly_responses,
            total=len(anomaly_responses)
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取异常列表失败: {str(e)}")


@router.post("/zones/stats", response_model=LightingStatsResponse)
async def get_zone_lighting_stats(request: LightingZoneStatsRequest):
    """
    获取区域照明统计
    """
    try:
        stats = await lighting_detection_service.get_zone_lighting_stats(
            zone_id=request.zone_id,
            days=request.days
        )
        
        return LightingStatsResponse(**stats)
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取区域统计失败: {str(e)}")


@router.get("/stats", response_model=LightingServiceStatsResponse)
async def get_service_stats():
    """
    获取照明检测服务统计
    """
    try:
        stats = lighting_detection_service.get_statistics()
        
        return LightingServiceStatsResponse(**stats)
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取服务统计失败: {str(e)}")


@router.post("/zones/config", response_model=LightingZoneConfigResponse)
async def create_zone_config(request: LightingZoneConfigRequest):
    """
    创建区域照明配置
    """
    try:
        # 创建区域配置
        config = LightingZoneConfig(
            zone_id=request.zone_id,
            zone_name=request.zone_name,
            zone_type=request.zone_type,
            optimal_brightness_range=request.optimal_brightness_range,
            optimal_color_temp_range=request.optimal_color_temp_range,
            natural_light_weight=request.natural_light_weight,
            energy_saving_mode=request.energy_saving_mode,
            operating_hours=request.operating_hours
        )
        
        # 添加到服务
        lighting_detection_service.add_zone_config(config)
        
        return LightingZoneConfigResponse(
            zone_id=config.zone_id,
            zone_name=config.zone_name,
            zone_type=config.zone_type,
            optimal_brightness_range=config.optimal_brightness_range,
            optimal_color_temp_range=config.optimal_color_temp_range,
            natural_light_weight=config.natural_light_weight,
            energy_saving_mode=config.energy_saving_mode,
            operating_hours=config.operating_hours
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建区域配置失败: {str(e)}")


@router.get("/zones/config", response_model=LightingZoneConfigListResponse)
async def get_zone_configs():
    """
    获取所有区域照明配置
    """
    try:
        configs = lighting_detection_service.get_zone_configs()
        
        # 转换为响应格式
        config_responses = []
        for config in configs:
            config_response = LightingZoneConfigResponse(
                zone_id=config.zone_id,
                zone_name=config.zone_name,
                zone_type=config.zone_type,
                optimal_brightness_range=config.optimal_brightness_range,
                optimal_color_temp_range=config.optimal_color_temp_range,
                natural_light_weight=config.natural_light_weight,
                energy_saving_mode=config.energy_saving_mode,
                operating_hours=config.operating_hours
            )
            config_responses.append(config_response)
        
        return LightingZoneConfigListResponse(
            configs=config_responses,
            total=len(config_responses)
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取区域配置失败: {str(e)}")


@router.get("/zones/config/{zone_id}", response_model=LightingZoneConfigResponse)
async def get_zone_config(zone_id: str):
    """
    获取指定区域的照明配置
    """
    try:
        configs = lighting_detection_service.get_zone_configs()
        
        # 查找指定区域的配置
        target_config = None
        for config in configs:
            if config.zone_id == zone_id:
                target_config = config
                break
        
        if not target_config:
            raise HTTPException(status_code=404, detail=f"未找到区域 {zone_id} 的配置")
        
        return LightingZoneConfigResponse(
            zone_id=target_config.zone_id,
            zone_name=target_config.zone_name,
            zone_type=target_config.zone_type,
            optimal_brightness_range=target_config.optimal_brightness_range,
            optimal_color_temp_range=target_config.optimal_color_temp_range,
            natural_light_weight=target_config.natural_light_weight,
            energy_saving_mode=target_config.energy_saving_mode,
            operating_hours=target_config.operating_hours
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取区域配置失败: {str(e)}")


@router.put("/zones/config/{zone_id}", response_model=LightingZoneConfigResponse)
async def update_zone_config(zone_id: str, request: LightingZoneConfigRequest):
    """
    更新区域照明配置
    """
    try:
        # 创建新的配置（覆盖原有配置）
        config = LightingZoneConfig(
            zone_id=zone_id,
            zone_name=request.zone_name,
            zone_type=request.zone_type,
            optimal_brightness_range=request.optimal_brightness_range,
            optimal_color_temp_range=request.optimal_color_temp_range,
            natural_light_weight=request.natural_light_weight,
            energy_saving_mode=request.energy_saving_mode,
            operating_hours=request.operating_hours
        )
        
        # 更新服务中的配置
        lighting_detection_service.add_zone_config(config)
        
        return LightingZoneConfigResponse(
            zone_id=config.zone_id,
            zone_name=config.zone_name,
            zone_type=config.zone_type,
            optimal_brightness_range=config.optimal_brightness_range,
            optimal_color_temp_range=config.optimal_color_temp_range,
            natural_light_weight=config.natural_light_weight,
            energy_saving_mode=config.energy_saving_mode,
            operating_hours=config.operating_hours
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新区域配置失败: {str(e)}")


@router.delete("/zones/config/{zone_id}")
async def delete_zone_config(zone_id: str):
    """
    删除区域照明配置
    """
    try:
        # 检查配置是否存在
        configs = lighting_detection_service.get_zone_configs()
        config_exists = any(config.zone_id == zone_id for config in configs)
        
        if not config_exists:
            raise HTTPException(status_code=404, detail=f"未找到区域 {zone_id} 的配置")
        
        # 从服务中删除配置
        if zone_id in lighting_detection_service.zone_configs:
            del lighting_detection_service.zone_configs[zone_id]
        
        return {"message": f"区域 {zone_id} 的配置已删除"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除区域配置失败: {str(e)}")


@router.post("/service/start")
async def start_service():
    """
    启动照明检测服务
    """
    try:
        await lighting_detection_service.start_service()
        return {"message": "照明检测服务已启动"}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"启动服务失败: {str(e)}")


@router.post("/service/stop")
async def stop_service():
    """
    停止照明检测服务
    """
    try:
        await lighting_detection_service.stop_service()
        return {"message": "照明检测服务已停止"}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"停止服务失败: {str(e)}")


@router.get("/service/status")
async def get_service_status():
    """
    获取照明检测服务状态
    """
    try:
        return {
            "running": lighting_detection_service._running,
            "monitoring_interval": lighting_detection_service.monitoring_interval,
            "total_detections": len(lighting_detection_service.detection_results),
            "total_anomalies": len(lighting_detection_service.anomalies),
            "total_zone_configs": len(lighting_detection_service.zone_configs)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取服务状态失败: {str(e)}")